<?

//Class to represent an order and the items in that order..

	include_once("cmsConfig.php");
		

	class CmsOrderContainer extends  CmsKVC  {
		
		
		var $currentOrderItemId;
		var $orderItems;
		
		function CmsOrderContainer(){
			parent::CmsKVC();
			$this->orderItems = array();
			$this->currentOrderItemId = null;
			//keys are values that are extracted automatically 
			$this->keys = array_merge_recursive(
				array( 
					EXTRACT_STRING => array("firstName","lastName","email","verifyEmail","phone","phoneNight","mobile","street","suburb","city","country","comments")
				),
				array(
					EXTRACT_BOOLEAN => array ("addressFormHasDisplayed")
				),
				$this->keys
			);
			$this->requiredKeys = array_merge(
				array("firstName","lastName","email","verifyEmail","phone","street","city","country"),
				$this->requiredKeys
			);
			$this->dataModelKeyMapping = 
				array_merge(
					$this->dataModelKeyMapping,
					array(	
						"firstName"=>"authordepartment",
						"lastName"=>"organisationalname",
						"email"=>"authorbio",
						"phone"=>"value",
						"phoneNight"=>"inhouse",
						"mobile"=>"restricted",						
						"street"=>"address",
						"suburb"=>"phone",
						"city"=>"fax",
						//"region" => "email",//
						"country"=>"url",						
						"comments"=>"headline",
						"price" => "extra1",//call the kvc method for price
						"shippingPrice" => "extra2",// call the kvc method for shippingPrice
						"totalPrice" => "extra3",//call the kvc method for total price
						"status" => "extra4",
						//"settlementdate" => "documentyear",
						"authCode" => "extra5",
						
						"pxSend" => "shortdescription",
						"pxReceive" => "content",
						"responseText" => "title",
						"transactionDate" => "documentdate"
				));
			$this->formId = 167;
			$this->documentTypeCode = 'docOrder';
			$this->orderItemClass = CMS_ORDERITEM_CLASS;
		}
				
		function &orderItemWithId($id) {
			$NULL = null;
			if (key_exists($id, $this->orderItems) && !is_null($this->orderItems[ $id ]))
				return $this->orderItems[ $id ];
			else {
				return $NULL;
			}
		}
		
		function setOrderItemWithId($id, &$orderItem ) {
			if (is_null($orderItem) || is_null($id)) return;
			$this->orderItems[ $id ] = &$orderItem;
		}				
		
		function &orderItems() {
			return $this->orderItems;
		}
		
		function removeOrderItemWithId($id){
			if(key_exists($id, $this->orderItems))  
				unset($this->orderItems[ $id ]);
				
			$cid = $this->valueForKey('currentOrderItemId');
			if ( !is_null($cid) && $cid == $id) $this->takeValueForKey(null, 'currentOrderItemId');

		}
		
		function price(){
			$price =0;
			foreach ($this->valueForKey('orderItems') as $oi) {
				$price +=  ($oi->valueForKey('price') * $oi->valueForKey('quantity'));
			}
			return $price;
		}
		
		
		function shippingPrice(){
			return 0;
		}
		
		function totalPrice(){
			return $this->valueForKey('price') + $this->valueForKey('shippingPrice');
		}
		
		function validateForSave(){
			$valid = parent::validateForSave();
			$keys = array_keys($this->orderItems);
			foreach ($keys as $key ){
				$oi = $this->orderItems[ $key ];
				$oiv = $oi->validateForSave();
				if (!$oiv) $valid = false;				
				$this->orderItems[$key] = $oi;

			}
			
			//additionally we need to check.. that we have order items..
			if (count($this->valueForKey('orderItems')) <= 0 ) {
				$valid = false;
				if (!is_array($this->valueForKey('invalidKeys'))){
					$invalidItems = array();
				} else {
					$invalidItems = $this->valueForKey('invalidKeys');
				}
				//array_push($invalidItems,'orderItems');
				$invalidItems['orderItems'] = 'orderItems';
				
				$this->takeValueForKey($invalidItems, 'invalidKeys');
			}	
			
						
			return $valid;
		}
		
		function save(&$authInfo, &$db ){
			$res = parent::save($authInfo, $db);
			if (is_null($res) || !$res->hasErrors){
				//delete old order items if any ..
				$query = "DELETE FROM content WHERE author='".$this->id."' AND formid = '168' ";
				$db->executeQuery($query);
				
				//iterate through and persist the order items..
				foreach ($this->orderItems as $oik=>$oi){
					if (!is_null($oi)){
						$oir = $oi->save($authInfo, $db);
						//how do we handle oir.. not sure yet
						//echo $oi->valueForKey('id');
						//myPrintR($oir);
						if ($oir->hasErrors) {
							$res->hasErrors = true;
							$res->addValidationMessageForKey('orderItemWithId_'. $oi->valueForKey('id') ,'f_CHILD_OBJEC_FAILED_TO_SAVE',CMS_STATUS_ERROR);
							return $res;
						} else {
							$this->orderItems[$oik] =  $oi;						
						}
						
					}
				}
				
			}
			return $res;
		}
		//achtung .. this is a descrtuctive operation.. it is called when the container wakes up.
		//all empty items are purged.. fromt the array..
		function purgeEmptyOrderItems(){
			$emptyItems = array();
			foreach ($this->orderItems as $id => $oi) {
				if (is_null($oi)) {
					array_push($emptyItems,$id );
					continue;
				}
				if ($oi->valueForKey('isEmpty'))
					array_push($emptyItems, $id);
			}
			$cid = $this->valueForKey('currentOrderItemId');
			while ($id = array_pop($emptyItems)){
				unset($this->orderItems[$id]);
				if ( !is_null($cid) && $cid = $id){
					$this->currentOrderItemId = null;
				}				
			}
			
		}
		
		function purgeInvalidOrderItems(){
			//loop through and remove all of the invalid order items.
			$orderItemKeys = array_keys($this->orderItems);
			foreach ($orderItemKeys as $oid){
				$oi = $this->orderItemWithId($oid);
				if (!is_null($oi)) {
					if (!$oi->validateForSave())
						$this->removeOrderItemWithId($oid);
				}
			}
		}
		
		function takeValuesFromRequest() {
			parent::takeValuesFromRequest();
			//populate my orderitems
			//foreach ($this->orderItems as $id => $oi ){
			//	$oi->takeValuesFromRequest();
			//	$this->setOrderItemWithId($id, $oi);
			//}
			$keys = array_keys($this->orderItems);
			foreach ($keys as $key ){
				$oi = $this->orderItems[ $key ];
				$oi->takeValuesFromRequest();
				$this->orderItems[$key] = $oi;
			}
		}
		
		function load( $id, &$authInfo, &$db) {
			$res = parent::load($id, $authInfo, $db);
			
			if ($res) {//if okay we need to find the orderitems..

				$orderItems = array();
				//find
				$q= "SELECT DISTINCT(categorycode) AS id,  formid FROM content WHERE formid='".CMS_ORDERITEM_FORMID."' AND author='" . $this->valueForKey('id') . "'";
				//return good here...
				$db->executeQuery($q);
					
				while ($row = $db->nextAssoc()){
					array_push($orderItems, $row);
				}
		

				$row=null;
				//while ($row = array_pop($orderItems)){
				foreach ($orderItems as $oirow){
					//var 
					$name = "oi_" . $oirow['id'];
					${ $name } = null;
					${ $name } = new $this->orderItemClass();
					//print_r(${ $name});
					if (!is_null($oirow)){
						${ $name }->load($oirow['id'], $authInfo, $db);
						$this->setOrderItemWithId(${ $name }->valueForKey('id'), ${ $name });
					}
				}
			}
			return $res;
		}
		
		
		function setOrderStatus($status) {
			//$this->takeValueForKey($status, 'status');
			if (in_array($status,$this->orderStatusTypes)){
				$this->dict['status'] = $status;
			}
		}
		
		function status(){
			if ( ! key_exists('status', $this->dict) || is_null($this->dict['status'])){
				$this->dict['status'] = ORDER_STATUS_NEW;
			}
			return $this->dict['status'];
		}
		
		
		//we check the email addresses here and confirm that they are correct
		function validateEmail() {
			$email = $this->valueForKey('email');
			if (!isEmailAddress($email)){
				return VALIDATION_INVALID_EMAIL_ADDRESS;
			}
			$verifyEmail = $this->valueForKey('verifyEmail');
			if ( $email !== $verifyEmail ) 
				return VALIDATION_EMAIL_ADDRESSES_DONT_MATCH;
			return true;
			
		}
		
		function validateVerifyEmail(){
			$verifyEmail = $this->valueForKey('verifyEmail');
			if (!isEmailAddress($verifyEmail)){
				return VALIDATION_INVALID_EMAIL_ADDRESS;
			}
			$email = $this->valueForKey('email');
			if ( $email !== $verifyEmail ) 
				return VALIDATION_EMAIL_ADDRESSES_DONT_MATCH;
			return true;
		}
		
		function cancelOrder($authInfo, &$db) {
			//if we have a documentcode we can clean purge and save the cancelled order
			//if (is_null($this->documentCode)) {
			//	//$this->purgeEmptyOrderItems();
			//	$this->purgeInvalidOrderItems();
			//	$this->takeValueForKey( ORDER_STATUS_CANCELLED, 'status');
			//	$res = $this->validateForSave();
			//	if ($res){
			//		$this->save($authInfo, $db);
			//	}
			}
			
		function cmsDocument() {
			$db = &$_SESSION['db'];
			return new CmsDocument($db);
		}
		
		function purgeOldOrderItems(&$authInfo, &$db){
			//delete old order items if any ..
			$query = "DELETE FROM content WHERE author='".$this->id."'";
			$db->executeQuery($query);
		}		
	}
	